package com.thomsonreuter.search.compare.comparision;

import com.google.common.base.Strings;
import com.thomsonreuter.search.compare.data.Comparison;
import com.thomsonreuter.search.compare.excutor.ElasticExecutor;
import com.thomsonreuter.search.compare.output.ReportWriter;
import org.skyscreamer.jsonassert.JSONCompareResult;

import java.io.IOException;
import java.util.List;
import static com.thomsonreuter.search.compare.comparision.JsonComparer.compareJSON;
import static java.util.stream.Collectors.toList;
import static org.skyscreamer.jsonassert.JSONCompareMode.NON_EXTENSIBLE;

public class ElasticComparator {


    private List<String> documentIds = null;

    public void compare(String fromIndex, String toIndex) throws IOException {

        String fromContent = ElasticExecutor.retriveQueryResponseContent(fromIndex);
        if(fromContent == null){
            System.out.println("Search index " + fromIndex + "is unreachable. ");
            reportResult(fromIndex,toIndex,null);
            return;
        }
        documentIds = ElasticExecutor.getDocumentIds(fromContent);
        String documentType = ElasticExecutor.getDocumentTypes(fromContent).get(0);
        final List<Comparison> results = documentIds.parallelStream().map(id -> compareDocument(id,fromIndex,toIndex,documentType)).collect(toList());
        reportResult(fromIndex,toIndex,results);

    }

    private void reportResult(String fromIndex, String toIndex, List<Comparison> results){
        try(ReportWriter reportWriter = new ReportWriter()){
            reportWriter.report(fromIndex,toIndex,results);
        } catch (IOException e) {
            System.out.println("Report compare result failed because:" + e.getMessage());
        }
    }

    public Comparison compareDocument(String documentId,String fromIndex, String toIndex,String documentType){

        try {
            String fromDocumentContent = ElasticExecutor.getDocContentById(fromIndex, documentType,documentId);
            String toDocumentContent = ElasticExecutor.getDocContentById(toIndex,documentType,documentId);
            JSONCompareResult compareResult = null;
            if (!Strings.isNullOrEmpty(toDocumentContent)) {
                compareResult = compareJSON(fromDocumentContent, toDocumentContent, NON_EXTENSIBLE);
            }
            return new Comparison(documentId,compareResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
